<?php
namespace Admin\Controller;
use Common\Model\AttachmentGroupModel;
use Common\Model\AttachmentModel;
use Common\uploadStorage\Local;
use Common\uploadStorage\Qiniu;
use Common\Util\BaseData;

class UploadController extends AdminController {
    protected $driver_type;
    protected $this_app_setting;
    public function _initialize()
    {
        parent::_initialize();
        $this->this_app_setting = BaseData::getAppSetting();
        $this->driver_type = $this->this_app_setting['storage_default']?$this->this_app_setting['storage_default']:'local'; //local qiniu  上传驱动
    }
    /**
     * 附件列表
     */
    public function fileList(){
        $attachment_m = new AttachmentModel();
        $attachment_group_m = new AttachmentGroupModel();
        $group_id = $_GET['group_id']?intval($_GET['group_id']):-1;
        $file_type = $_GET['fileType']?trim($_GET['fileType']):'image';
        $page = $_GET['page']?intval($_GET['page']):1;
        $pagesize = 32;
        $where = [];
        if(!empty($group_id) && $group_id != -1){
            $where['group_id'] = $group_id;
        }
        if($file_type == 'file'){
            $where['ext'] = ['in',['txt','zip','arr','pem','crt']];
        }else if($file_type == 'video'){
            $where['ext'] = ['in',['mp3','mp4']];
        }else{
            $where['ext'] = ['in',['gif','jpg','jpeg','bmp','png']];
        }
        $att_list = $attachment_m->getAccachmentList($where,'',$page,30);
        foreach ($att_list as $key=>$val){
            if($val['storage'] == 'local'){
                $att_list[$key]['file_true_path'] = C('WEB_WWW_URL').'/'.$val['path'].$val['url'];
                if($file_type == 'file'){
                    $att_list[$key]['file_true_path'] = '/'.$val['path'].$val['url'];
                }
            }else if($val['storage'] == 'qiniu'){
                $att_list[$key]['file_true_path'] = $val['url'];
            }
            $att_list[$key]['file_type'] = $file_type;
            if($file_type == 'file'){
                $att_list[$key]['bg_img'] = C('WEB_WWW_URL').'/Public/filemanage/bg_file.png';
            }else if($file_type == 'video'){
                $att_list[$key]['bg_img'] = C('WEB_WWW_URL').'/Public/filemanage/bg_video.png';
            }else{
                $att_list[$key]['bg_img'] = $att_list[$key]['file_true_path'];
            }
        }
        $file_list['data'] = $att_list;

        $total_num = $attachment_m->where($where)->count('id');
        $file_list['total'] = $total_num?$total_num:0;
        $file_list['per_page'] = $pagesize;
        $file_list['current_page'] = $page;
        $file_list['last_page'] = ceil($total_num/$pagesize);
        //图片分组
        $group_list = $attachment_group_m->order('sort Asc,group_id Asc')->select();

        $this->renderSuccess(['file_type'=>$file_type,'file_list'=>$file_list,'group_list'=>$group_list?$group_list:[]]);
    }

    /**
     * 上传图片
     */
    public function image(){
        $attachment_m = new AttachmentModel();
        $driver_type = $this->driver_type;

        $group_id = $_POST['group_id']?intval($_POST['group_id']):-1;
        $file_type = $_POST['file_type']?trim($_POST['file_type']):'image';
        $file_accept_ext = $_POST['file_accept_ext']?trim($_POST['file_accept_ext']):'';
        if(empty($file_accept_ext)) $this->renderError('未指定文件上传格式！');

        $upload_file = $_FILES['iFile'];
        // 要上传图片的本地路径
        $realPath = $upload_file['tmp_name'];
        // 文件扩展名
        $ext = pathinfo($upload_file['name'], PATHINFO_EXTENSION);
        // 文件md5
        $file_md5 = hash_file('md5', $realPath);
        if($att_info = $attachment_m->getAttachmentInfoByMd5($file_md5)){
            $this->renderError('文件MD5已存在，上传失败！');
        }
        // 自动生成文件名
        $file_name = date('YmdHis') . substr(md5($realPath), 0, 5)
            . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        // 文件全名
        $file_true_name = $file_name .'.'.$ext;
        $root_path = 'Data/upload/';//保存目录
        $sub_path = date('Y-m-d',time());//保存子目录
        //如果是本地驱动或者文件类型为附件
        if($driver_type == 'local' || $file_type == 'file'){
            $driver_type = 'local';
            $server_upload = new Local();
            if (!$server_upload->upload($upload_file,[
                'maxSize' => 2 * 1024 * 1024,
                'exts' => explode(',',$file_accept_ext),
                'rootPath' => $root_path,
                'saveName' => $file_name,
                'subName'  => array('date','Y-m-d'),
            ])) {
                $this->renderError('图片上传失败'.$server_upload->getError());
            }

            $att_data['path'] = $root_path.$sub_path.'/';
            $att_data['url'] = $file_true_name;
            $att_data['file_true_path'] = C('WEB_WWW_URL').'/'.$att_data['path'].$att_data['url'];
            if($file_type == 'file'){
                $att_data['file_true_path'] = '/'.$att_data['path'].$att_data['url'];
            }
        }else if($driver_type == 'qiniu'){
            $server_upload = new Qiniu();
            if(!$server_upload->upload($upload_file,[
                'bucket'=>$this->this_app_setting['storage_qiniu_bucket'],
                'access_key'=>$this->this_app_setting['storage_qiniu_access_key'],
                'secret_key'=>$this->this_app_setting['storage_qiniu_secret_key'],
                'domain'=>$this->this_app_setting['storage_qiniu_domain'],
                'file_name'=>$root_path.$sub_path.'/'.$file_true_name
            ])){
                $this->renderError('图片上传失败'.$server_upload->getError());
            }

            $att_data['path'] = '';
            $att_data['url'] = $this->this_app_setting['storage_qiniu_domain'].'/'.$root_path.$sub_path.'/'.$file_true_name;
            $att_data['file_true_path'] = $att_data['url'];
        }else{
            $this->renderError('非法上传驱动！');
        }

        if($file_type == 'file'){
            $att_data['bg_img'] = C('WEB_WWW_URL').'/Public/filemanage/bg_file.png';
        }else if($file_type == 'video'){
            $att_data['bg_img'] = C('WEB_WWW_URL').'/Public/filemanage/bg_video.png';
        }else{
            $att_data['bg_img'] = $att_data['url'];
        }

        $att_data['storage'] = $driver_type;
        $att_data['user_id'] = 0;
        $att_data['group_id'] = $group_id;
        $att_data['name'] = $upload_file['name'];
        $att_data['module'] = 'admin';
        $att_data['thumb'] = '';
        $att_data['mime'] = $upload_file['type'];
        $att_data['ext'] = $ext;
        $att_data['size'] = $upload_file['size'];
        $att_data['md5'] = $file_md5;
        $att_data['sha1'] = $file_md5;
        $att_data['driver'] = $driver_type;
        $att_data['create_time'] = time();
        $att_data['update_time'] = 0;
        $att_data['listorders'] = 0;
        $att_data['status'] = 1;
        if($att_data['id'] = $attachment_m->createAttachment($att_data)){
            $this->renderSuccess($att_data,'图片上传成功');
        }else{
            $this->renderError('图片上传失败，请重试');
        }
    }

    /**
     * 删除文件
     */
    public function deleteFiles(){
        $attachment_m = new AttachmentModel();
        $filedIds = $_POST['fileIds'];
        if(empty($filedIds)) $this->renderError('请选择要删除的文件');
        if(!$data_list = $attachment_m->where(['id'=>['in',$filedIds]])->select()){
            $this->renderError('请选择要删除的文件');
        }
        //只删除数据库
        if($attachment_m->where(['id'=>['in',$filedIds]])->delete()){
            $this->renderSuccess([],'删除成功');
        }else{
            $this->renderError('删除失败，请重试');
        }

        foreach ($data_list as $key=>$val){
            if($val['storage'] == 'local'){
                $server_upload = new Local();
                if($server_upload->deleteFile($val)){
                    $attachment_m->where(['id'=>$val['id']])->delete();
                }
            }else if($val['storage'] == 'qiniu'){
                $server_upload = new Qiniu();
                if($server_upload->deleteFile($val)){

                }
            }
        }
    }

    /**
     * 新增分组
     */
    public function addGroup(){
        $attachment_group_m = new AttachmentGroupModel();
        $group_type = $_POST['group_type']?trim($_POST['group_type']):'image';
        $group_name = $_POST['group_name']?trim($_POST['group_name']):'';
        if(empty($group_name)) $this->renderError('请输入分组名称');
        if($group_info = $attachment_group_m->where(['group_name'=>$group_name])->find()){
            $this->renderError('分组已存在，新增失败！');
        }
        $g_add_data['group_type'] = $group_type;
        $g_add_data['group_name'] = $group_name;
        $g_add_data['sort'] = 100;
        $g_add_data['create_time'] = time();
        $g_add_data['group_id'] = $attachment_group_m->add($g_add_data);
        $this->renderSuccess($g_add_data,'新增成功');
    }

    /**
     * 编辑分组
     */
    public function editGroup(){
        $attachment_group_m = new AttachmentGroupModel();
        $group_id = $_POST['group_id']?intval($_POST['group_id']):0;
        $group_name = $_POST['group_name']?trim($_POST['group_name']):'';
        if(empty($group_id)) $this->renderError('非法操作');
        if(empty($group_name)) $this->renderError('请输入分组名称');
        if(!$group_info = $attachment_group_m->where(['group_id'=>$group_id])->find()){
            $this->renderError('分组不存在，修改失败！');
        }
        $attachment_group_m->where(['group_id'=>$group_id])->save(['group_name'=>$group_name,'update_time'=>time()]);
        $this->renderSuccess([],'修改成功');
    }

    /**
     * 删除分组
     */
    public function deleteGroup(){
        $attachment_m = new AttachmentModel();
        $attachment_group_m = new AttachmentGroupModel();
        $group_id = $_POST['group_id']?intval($_POST['group_id']):0;
        if(!$group_info = $attachment_group_m->where(['group_id'=>$group_id])->find()){
            $this->renderError('分组不存在，删除失败！');
        }
        $attachment_m->where(['group_id'=>$group_id])->save(['group_id'=>-1,'upate_time'=>time()]);
        $attachment_group_m->where(['group_id'=>$group_id])->delete();
        $this->renderSuccess([],'删除成功');
    }
}